/**
 * mvc pattern - proxy
 * Copyright (c) 2009 cmiscm.com
 * date of final modification : 2009. 11. 19 
*/
package com.cmiscm.mvc
{
	import __AS3__.vec.Vector;
	
	/**
     * MVC Proxy - Singleton Pattern.
     * 
     * @example
     * <listing>
     * // Add Proxy
     * Model.getInstance.addProxy(MenuProxy.NAME, new MenuProxy());
     * 
     * // Get Proxy
     * var menu:MenuProxy = Model.getInstance.getProxy(MenuProxy.NAME) as MenuProxy;
     * 
     * // Remove Proxy
     * Model.getInstance.removeProxy(MenuProxy.NAME);
     * </listing>
     * 
     * @see com.cmiscm.mvc.IModel IModel
     */	
    public class Model extends Object
    {       
        private var _proxyVector:Vector.<IModel> = new Vector.<IModel>();
        private var _nameVector:Vector.<String> = new Vector.<String>();
        
        private const NO_FOUND_MSG:String = "Proxy name is no found";
        private const ALREADY_MSG:String = "Proxy Name is already in use";
        private const SINGLETON_MSG:String = "Singleton already constructed";        
        private static var _instance:Model;

        public function Model()
        {
			super();
            if (_instance != null) throw Error(SINGLETON_MSG);
            _instance = this;
        }
        public static function get getInstance():Model
        {
            if (_instance == null) _instance = new Model();
            return _instance;
        }
		
        /**
         * Get Proxy 
         * <p>
         * return null in case not find Proxy
         * </p>
         * @param $name Proxy Name
         * @return 
         * 
         */ 	
        public function getProxy($name:String):IModel
        {
            var index:int = _nameVector.indexOf($name);
            if (index == -1) {
                return null;
            } else {
            	return _proxyVector[index];
            }
        }
        
		/**
		 * Add Proxy  
		 * @param $name Proxy Name
		 * @param $proxy Proxy implements <code>IModel</code>
		 * 
		 */        
		public function addProxy($name:String, $proxy:IModel):void
        {
            var index:int = _nameVector.indexOf($name);
            if (index == -1) {
                _proxyVector.push($proxy);
                _nameVector.push($name);
            } else {
                throw Error(ALREADY_MSG);
            }
        }
        
        /**
         * Remove Proxy  
         * @param $name Proxy Name
         * 
         */       
        public function removeProxy($name:String):void
        {
            var index:int = _nameVector.indexOf($name);
            if (index == -1) {
                throw Error(NO_FOUND_MSG);
            } else {
            	_proxyVector[index] = null;
	            _nameVector[index] = null;
	            _proxyVector.splice(index, 1);
	            _nameVector.splice(index, 1);
            }
        }       

    }
}
